<?
  session_start();
  if(isset($_SESSION['loginerror'])) $loginerror = $_SESSION['loginerror'];
  if(!isset($_SESSION['validuser'])){
    print $loginerror;
    print "<form method='post' action='verifyuser.php'>";
    print "<table id='loginform' style='margin: 50px auto 0 auto'>";
    print "<tr><th>Username:</td><td><input type='text' name='uname'></td></tr>";
    print "<tr><th>Password:</td><td><input type='password' name='pword'></td></tr>";
    print "<tr><th colspan='2'><button type='submit'>Login</button></td></tr>";
    print "</table>";
    print "</form>";
    exit();
  }
?>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link href="/css/jquery-ui-1.10.3.custom.min.css" type="text/css" rel="stylesheet">
<script src="fileupload/jquery.fileupload.js"></script>

<script src="http://jwpsrv.com/library/sxJ+CDP1EeOfyxIxOUCPzg.js"></script>

<?
  $bucket = "rdp-music";
  $accesskey = "AKIAJIZQG4MAPIGZRPCA";
  $secret = "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";
  $key = uniqid() . ".mp3";

  $now = strtotime(date("Y-m-d\TG:i:s"));
  $expire = date('Y-m-d\TG:i:s\Z', strtotime('+ 10 hours', $now)); // credentials valid 10 minutes from now

  $policy = '{
              "expiration": "' . $expire . '",
              "conditions": [
                  {
                      "bucket": "' . $bucket . '"
                  },
                  {
                      "acl": "public-read"
                  },
                  [
                      "starts-with",
                      "$key",
                      ""
                  ],
                  {
                      "success_action_status": "201"
                  },
                  [
                    "starts-with",
                    "$Content-Type",
                    ""
                  ]
              ]
          }';

  $base64Policy = base64_encode($policy);
  $signature = base64_encode(hash_hmac("sha1", $base64Policy, $secret, $raw_output = true));

  include(dirname(__FILE__) . "/database.inc.php");
  $db = new database(dirname(__FILE__) . "/streaming.rdb");

  $l = $db->query("SELECT * FROM track");
?>

<style>
  #tracklist{
    border-collapse: collapse;
    border-top: 1px solid black;
    border-left: 1px solid black;
    margin: 10px;
  }

  #tracklist td, #tracklist th{
    border-right: 1px solid black;
    border-bottom: 1px solid black;
    padding: 10px;
  }

  .deltrack{
    float: left;
    cursor: pointer;
  }

  .progress {
      position: relative;
      top: 20px;
      width: 300px;
      height: 15px;
      background: #C7DA9F;
      border-radius: 10px;
      overflow: hidden;
      display: none;
  }

  .bar {
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 15px;
      background: #85C220;
  }

  #uploadform{
    display: none;
  }

  #uploadform table{
    border-collapse: collapse;
  }

  #uploadform table td, #uploadform table th{
    padding: 5px 5px 10px 5px;
    vertical-align: top;
  }

  #uploadform table th{
    text-align: right;
  }

  #uploadform table td{
    text-align: left;
  }

  #uploadform input, #uploadform textarea{
    width: 500px;
  }

  #duration{
    width: auto;
  }

  #detail_form{
    display: none;
  }
</style>

<div id="uploadform">
  <form action="//s3.amazonaws.com/<?php echo $bucket; ?>/" method="POST" enctype="multipart/form-data" class="direct-upload">

      <!-- We'll specify these variables with PHP -->
      <!-- Note: Order of these is Important -->
      <input type="hidden" name="key" value="<?= $key; ?>">
      <input type="hidden" name="AWSAccessKeyId" value="<?php echo $accesskey; ?>">
      <input type="hidden" name="acl" value="public-read">
      <input type="hidden" name="success_action_status" value="201">
      <input type="hidden" name="policy" value="<?php echo $base64Policy; ?>">
      <input type="hidden" name="signature" value="<?php echo $signature; ?>">
      <input type="hidden" name="Content-Type" value="audio/mpeg">

      Select File: <input type="file" name="file" />

      <!-- Progress Bar to show upload completion percentage -->
      <div class="progress"><div class="bar"></div></div>

  </form>

  <form action="process-form-data.php" method="POST" id="detail_form">
    <input type="hidden" name="filename" id="upload_original_name" value="<?= $key; ?>">
    <table>
      <tr>
        <th>Title:</th>
        <td><input type="text" name="title" id="upload_custom_name"></td>
      </tr>
      <tr>
        <th>Duration (Seconds):</th>
        <td><input type="text" name="duration" id="duration" width="5" maxlength="5"></td>
      </tr>
      <tr>
        <th>Description:</th>
        <td><textarea rows="10" name="desc"></textarea></td>
      </tr>
      <tr>
        <th colspan="2">
          <button type="submit" onclick="window.onbeforeunload = null;">Continue</button>
        </th>
      </tr>
    </table>
  </form>

</div>

<button type="button" id="addtrack"><span class="ui-icon ui-icon-plus" title="Upload New Track"></span></button>
<table id="tracklist">
  <tr>
    <th>Title</th>
    <th>Description</th>
    <th>Player</th>
  </tr>
  <? foreach($l as $r): $pid = uniqid(); ?>
  <tr>
    <td><span class="ui-icon ui-icon-trash deltrack" title="Delete Track" id="<?= $r['serial']; ?>"></span>&nbsp;<?= $r['title']; ?></td>
    <td><?= $r['desc']; ?></td>
    <td>
      <div id="player<?= $pid; ?>"></div>
      <script type='text/javascript'>
        jwplayer('player<?= $pid; ?>').setup({
          file: "https://s3.amazonaws.com/rdp-music/<?= $r['filename']; ?>",
          image: 'http://www.longtailvideo.com/content/images/jw-player/lWMJeVvV-876.jpg',
          width: '400',
          height: '30'
        });
      </script>
    </td>
  </tr>
  <? endforeach; ?>
</table>

<script type="text/javascript">
  var uploadSuccess = true;
  $(function(){
    $("button").button();

    $(".deltrack").click(function(){
      $.post("/streaming/deletetrack.ajax.php", { "trackid": $(this).attr("id") }, function(d){
        location.reload();
      }, "text");
    });

    $("#addtrack").click(function(){
      $("#uploadform").dialog({
        modal: true,
        width: 800,
        height: 500
      });
    });


    $('.direct-upload').each( function() {
      var form = $(this);

      form.fileupload({
        url: form.attr('action'),
        type: 'POST',
        datatype: 'xml',
        add: function (event, data) {
          $(".progress").show();
          // Message on unLoad.
          window.onbeforeunload = function() {
            return 'You have unsaved changes.';
          };

          // Submit
          data.submit();
        },
        send: function(e, data) {
          // onSend
        },
        progress: function(e, data){
          // This is what makes everything really cool, thanks to that callback
          // you can now update the progress bar based on the upload progress.
          var percent = Math.round((data.loaded / data.total) * 100);
          $('.bar').css('width', percent + '%');
        },
        fail: function(e, data) {
          console.log(e);
          console.log(data);
          alert("Upload fail");
          $(".progress").hide();
          uploadSuccess = false;
          // Remove 'unsaved changes' message.
          window.onbeforeunload = null;
        },
        success: function(data) {
            // onSuccess
        },
        done: function (event, data) {
          console.log(data);
          if(uploadSuccess){
            // Fill the name field with the file's name.
            $('#upload_custom_name').val(data.originalFiles[0].name);
            $("#detail_form").show();
            $(".direct-upload").hide();
          }
        },
      });
    });
  });
</script>